import $apiFun from "../request/api";
import axios from "axios";
export function setInfo(infoData: any) {
    //  设置登录信息过期时间为12小时后
    const { id, auth_Token, pegg, name, v_way_id, head_icon } = infoData
    const expires = new Date().getTime() + 1000 * 60 * 60 * 12
    const data = { uid: id, auth_token: auth_Token, expires, v_way_id: v_way_id, pegg: pegg, name: name, head_icon: head_icon }
    localStorage.setItem('userInfo', JSON.stringify(data))
}

export function isLoggedIn() {
    try {
        let data = localStorage.getItem('userInfo')
        const userInfo = JSON.parse(data)
        const timeNow = new Date().getTime()    // 获取当前时间
        //  如果未登录或再登录时间超过1天，也即expires小于现在的时间，则登录失败并清除数据
        if (!userInfo) {
            return false
        } else if (userInfo.expires < timeNow) {
            localStorage.clear()
            return false
        } else {
            //  如果再登录有效期内，则登录成功，并更新expires为下一个12小时
            userInfo.expires = timeNow + 1000 * 60 * 60 * 12
            localStorage.setItem('userInfo', JSON.stringify(userInfo))
            return true
        }
    } catch (err) {
        throw err
    }
}
export function quit() {
    localStorage.removeItem('userInfo')
    return getUid()
}

export function getUid() {
    try {
        let data = localStorage.getItem('userInfo') || "{}"
        const userInfo = JSON.parse(data)
        if (!!userInfo)
            return userInfo.uid
    } catch (err) {
        throw err
    }
}
export function getName() {
    try {
        let data = localStorage.getItem('userInfo') || "{}"
        const userInfo = JSON.parse(data)
        if (!!userInfo)
            return userInfo.name
    } catch (err) {
        throw err
    }
}
export function getHeadImg() {
    try {
        let data = localStorage.getItem('userInfo') || "{}"
        const userInfo = JSON.parse(data)
        if (!!userInfo) {
            return userInfo.head_icon
        }
    } catch (err) {
        throw err
    }
}

export function getToken() {
    try {
        let data = localStorage.getItem('userInfo') || "{}"
        const userInfo = JSON.parse(data)
        if (!!userInfo)
            return userInfo.auth_token
    } catch (err) {
        throw err
    }
}
export async function upUserInfoData() {
    try {
        let data = {}
        await $apiFun.getUserInfo().then((res: any) => {
            if (res.code == 200) {
                setInfo(res.data)
            }
            data = res
        })
        return data
    } catch (err) {
        throw err
    }
}

export function getLocalData() {
    try {
        let data = localStorage.getItem('userInfo') || "{}"
        const userInfo = JSON.parse(data)
        if (!!userInfo)
            return userInfo
    } catch (err) {
        throw err
    }
}
export default isLoggedIn